<template>
  <div class="app-container">
    <el-row style="margin-bottom: 10px;">
      <el-col :span="6">
        <div class="title">
          <img src="../../../assets/icons/开放时间.png" alt="opentime" class="icon">
          <span>开放时间</span>
        </div>
      </el-col>
    </el-row>

    <el-row type="flex" justify="space-between" class="opentime-container">
      <el-col :span="8">
        <label for="open.morning">上午开放时间：</label>
        <el-time-picker
          v-model="morning"
          is-range
          range-separator="-"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          placeholder="选择时间范围"
          format="HH:mm"
          value-format="timestamp"
          @change="changOpentime_m"/>
      </el-col>
      <el-col :span="8">
        <label for="open.afternoon">下午开放时间：</label>
        <el-time-picker
          v-model="afternoon"
          is-range
          range-separator="-"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          placeholder="选择时间范围"
          format="HH:mm"
          value-format="timestamp"
          @change="changOpentime_a"/>
      </el-col>
      <el-col :span="6">
        <el-button type="primary" icon="el-icon-edit-outline" @click="setOpentime">设置开放时间</el-button>
        <el-button type="primary" icon="el-icon-refresh" @click="getOpenTime">重置</el-button>
      </el-col>
    </el-row>

    <el-row style="margin-bottom: 20px;">
      <el-col :span="6">
        <div class="title">
          <img src="../../../assets/icons/查询.png" alt="search" class="icon">
          <span>查询会议室</span>
        </div>
      </el-col>
    </el-row>

    <el-row class="filter-container">
      <el-select v-model="search" clearable placeholder="请选择查询方式" style="margin-right: 20px" @change="switchTip">
        <el-option v-for="item in searchBy" :key="item" :value="item" />
      </el-select>
      <span v-if="search === '会议室大小'">>=&nbsp;&nbsp;&nbsp;&nbsp;</span>
      <el-input
        v-show="notByOpentime"
        v-model="listQuery.query"
        :placeholder="tip"
        style="width: 30%;margin-right: 20px"
        class="filter-item"
        @keyup.enter.native="handleFilter" />
      <el-select v-show="!notByOpentime" v-model="listQuery.week">
        <el-option v-for="item in week" :key="item.value" :value="item.value" :label="item.label" />
      </el-select>
      <el-select v-show="!notByOpentime" v-model="listQuery.morning">
        <el-option v-for="item in isMorning" :key="item.value" :value="item.value" :label="item.label" />
      </el-select>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">查询</el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">添加</el-button>
    </el-row>

    <el-table v-loading="listLoading" :key="tableKey" :data="list" border fit highlight-current-row style="width: 100%;">
      <el-table-column label="会议室编号" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="会议室开放时间" align="center">
        <template slot-scope="scope">
          <el-popover placement="right" width="300" trigger="click">
            <el-table :data="gridData">
              <el-table-column width="100" property="week" label="周" />
              <el-table-column width="150" property="status" label="开放情况" />
            </el-table>
            <el-button slot="reference" type="text">点击查看详情</el-button>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="会议室大小" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.size }}</span>
        </template>
      </el-table-column>
      <el-table-column label="会议室类型" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.type ? '实验室' : '会议室' }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="会议室前端设备编号" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.device }}</span>
        </template>
      </el-table-column> -->
      <el-table-column label="多媒体设备" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.media ? '有' : '无' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="空调" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.airconditioner ? '有' : '无' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="楼层" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.floor }}楼</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" min-width="148px">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="handleUpdate(scope.$index,scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.$index,scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" append-to-body>
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="120px" style="width: 450px; margin-left:50px;">
        <el-form-item label="会议室编号">
          <el-input v-model="temp.id" />
        </el-form-item>
        <!-- <el-form-item label="会议室类型">
          <el-select v-model="temp.type" >
            <el-option v-for="item in roomType" :key="item.type" :label="item.name" :value="item.type"/>
          </el-select>
        </el-form-item> -->
        <el-form-item label="会议室开放时间">
          <el-input v-model="temp.opentime" type="number" />
        </el-form-item>
        <el-form-item label="会议室大小">
          <el-input v-model="temp.size" type="number" />
        </el-form-item>
        <el-form-item label="设备编号">
          <el-input v-model="temp.device" />
        </el-form-item>
        <el-form-item label="会议室设备">
          <el-checkbox v-model="temp.media" :true-label="1" :false-label="0">多媒体</el-checkbox>
          <el-checkbox v-model="temp.airconditioner" :true-label="1" :false-label="0">空调</el-checkbox>
        </el-form-item>
        <el-form-item label="楼层">
          <el-input v-model="temp.floor" type="number" />
        </el-form-item>
        <el-form-item label="权限(0-99)">
          <el-input-number v-model="temp.permission" :min="0" :max="99" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button v-if="dialogStatus == 'create'" type="primary" @click="createData">确认</el-button>
        <el-button v-else type="primary" @click="updateData">确认</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { findAllMeetingRoom, findMeetingRoomById, findMeetingRoomBySize, findMeetingRoomByOpenTime, addMeetingRoom, updateMeetingRoom, deleteMeetingRoom, getOpenTime, setOpenTime
} from '@/api/room'
import waves from '@/directive/waves' // 水波纹指令
import { parseTime } from '@/utils'
import { s2as } from '@/utils/opentime'

export default {
  name: 'MrmTable',
  directives: {
    waves
  },
  filters: {
    parseTime(time) {
      const date = new Date(time)
      return parseTime(date, '{y}-{m}-{d} {h}:{i}')
    }
  },
  data() {
    return {
      tableKey: 0,
      list: [],
      listLoading: true,
      gridData: [{
        week: '周一'
      },
      {
        week: '周二'
      },
      {
        week: '周三'
      },
      {
        week: '周四'
      },
      {
        week: '周五'
      },
      {
        week: '周六'
      },
      {
        week: '周日'
      }
      ],
      roomType: [
        {
          type: 0,
          name: '会议室'
        },
        {
          type: 1,
          name: '实验室'
        }],
      listQuery: {
        query: undefined,
        week: undefined,
        morning: undefined
      },
      notByOpentime: true,
      week: [
        {
          value: 'Mon',
          label: '周一'
        },
        {
          value: 'Tue',
          label: '周二'
        },
        {
          value: 'Wed',
          label: '周三'
        },
        {
          value: 'Thu',
          label: '周四'
        },
        {
          value: 'Fri',
          label: '周五'
        },
        {
          value: 'Sat',
          label: '周六'
        },
        {
          value: 'Sun',
          label: '周日'
        }
      ],
      isMorning: [
        {
          value: 0,
          label: '上午'
        },
        {
          value: 1,
          label: '下午'
        }
      ],
      temp: {
        id: '',
        type: undefined,
        opentime: undefined,
        size: undefined,
        device: '',
        permission: undefined,
        airconditioner: 0,
        media: 0,
        floor: undefined
      },
      open: {
        opens: '',
        opene: '',
        openas: '',
        openae: ''
      },
      morning: [],
      afternoon: [],
      searchBy: ['会议室编号', '会议室大小'], // , '会议室开放时间'
      search: '',
      tip: '',
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: 'Edit',
        create: 'Create'
      },
      rules: {
        username: [{
          required: true,
          message: 'username is required',
          trigger: 'blur'
        }],
        password: [{
          required: true,
          message: 'password is required',
          trigger: 'blur'
        }]
      }
    }
  },
  created() {
    this.getList()
  },
  mounted() {
    this.getOpenTime()
  },
  methods: {
    changOpentime_m(value) {
      this.open.opens = value[0]
      this.open.opene = value[1]
    },
    changOpentime_a(value) {
      this.open.openas = value[0]
      this.open.openae = value[1]
    },
    async getList() {
      this.listLoading = true
      // console.log(this.listQuery.query)
      if (!this.listQuery.query && !this.listQuery.week) {
        const res = await findAllMeetingRoom()
        this.list = res.data.data
        // console.log(this.list)
        // Just to simulate the time of the request
      } else {
        // console.log(this.listQuery)
        switch (this.search) {
          case '会议室编号':
          {
            const res = await findMeetingRoomById(this.listQuery.query)
            this.list = [res.data.data]
            break
          }
          case '会议室大小':
          {
            const res = await findMeetingRoomBySize(this.listQuery.query)
            this.list = res.data.data.content
            break
          }
          case '会议室开放时间':
          {
            const res = await findMeetingRoomByOpenTime(this.listQuery.week, this.listQuery.morning)
            this.list = res.data.data
            break
          }
          default:
          {
            break
          }
        }
      }
      this.list.forEach(data => {
        if (data.opentime) {
          data.status = s2as(data.opentime.toString(2))
          this.parseOpentime(data.status)
        // console.log(data)
        }
      })
      setTimeout(() => {
        this.listLoading = false
      }, 0.7 * 1000)
    },
    parseOpentime(openTimeArray) {
      for (let i = 0; i < openTimeArray.length; i++) {
        this.gridData[i].status = openTimeArray[i]
      }
      // console.log(this.gridData)
    },
    async getOpenTime() {
      const res = await getOpenTime()
      this.open = JSON.parse(res.data.data.v)
      this.morning = [this.open.opens, this.open.opene]
      this.afternoon = [this.open.openas, this.open.openae]
      // console.log(this.open)
    },
    async setOpentime() {
      let open = Object.assign({}, this.open)
      delete open.id
      open = JSON.stringify(open)
      // console.log(open)
      const res = await setOpenTime(open)
      if (res.data.code === 0) {
        this.$notify({
          title: '成功',
          message: '设置成功',
          type: 'success',
          duration: 2000
        })
      }
    },
    handleFilter() {
      this.getList()
    },
    switchTip() {
      const s = '请输入'
      switch (this.search) {
        case '会议室编号':
          this.notByOpentime = true
          this.tip = `${s}会议室编号`
          break
        case '会议室大小':
          this.notByOpentime = true
          this.tip = `${s}会议室大小`
          break
        case '会议室开放时间':
          this.notByOpentime = false
          break
        default:
          this.tip = ''
          break
      }
    },
    resetTemp() {
      this.temp = {
        id: '',
        opentime: undefined,
        size: undefined,
        device: '',
        permission: undefined,
        airconditioner: 0,
        media: 0,
        floor: undefined
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const room = Object.assign({}, this.temp)
          addMeetingRoom(room).then(res => {
            if (res.data.code === 0) {
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '创建成功',
                type: 'success',
                duration: 2000
              })
              this.getList()
            }
          })
        }
      })
    },
    handleUpdate(index, row) {
      this.temp.id = row.id
      this.temp.type = row.type
      this.temp.opentime = row.opentime
      this.temp.size = row.size
      this.temp.device = row.device
      this.temp.permission = row.permission
      this.temp.airconditioner = row.airconditioner
      this.temp.media = row.media
      this.temp.floor = row.floor
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const room = Object.assign({}, this.temp)
          updateMeetingRoom(room).then(res => {
            if (res.data.code === 0) {
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '更新成功',
                type: 'success',
                duration: 2000
              })
              this.getList()
            }
          })
        }
      })
    },
    handleDelete(index, row) {
      deleteMeetingRoom(row.id).then(res => {
        if (res.data.code === 0) {
          this.$notify({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
          this.getList()
        } else {
          this.$notify({
            title: '删除失败',
            message: '该会议室现有会议正在使用, 无法删除',
            type: 'error',
            duration: 2000
          })
        }
      })
    }
  }
}

</script>

<style lang="scss">
.opentime-container {
  .el-date-editor {
    margin-left: 7em;
    display: flex;
    width: auto;
    font-size: 20px;
    padding: 0;
    i {
      display: none;
    }
    .el-range-input {
      width: 42%;
      font-size: 20px;
    }
    .el-range-separator {
      font-size: 20px;
      line-height: 40px;
      padding: 0;
      margin: 0 2px;
    }
  }
  .el-input__inner {
    border: none;
  }
}

</style>

<style scoped>
  .filter-container,
  .opentime-container {
    margin-bottom: 30px;
    margin-left: 36px;
  }

  .filter-container label,
  .opentime-container label {
    float: left;
    line-height: 40px;
    font-size: 22px;
    font-weight: 400;
  }

</style>
